<template>
  <div class="app-container">
    <el-row class="library-row">
      <el-col :span="2">
        <el-select v-model="form.page_size" placeholder="每页条数">
          <el-option v-for="item in page" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-select v-model="form.search.grade_id" placeholder="选择年级">
          <el-option v-for="item in grade" :key="item.id" :label="item.grade_name" :value="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        <el-select v-model="form.search.class_id" placeholder="选择班级">
          <el-option
            v-for="item in classData"
            :key="item.id"
            :label="item.class_name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-input placeholder="关键字" v-model="form.search.username" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="searchData"></el-button>
        </el-input>
      </el-col>
      <el-col :span="10" :offset="5" class="add">
        <el-button @click="addUser" type="primary" icon="el-icon-plus">添加用户</el-button>
        <el-button @click="delUser(3)" type="danger" icon="el-icon-minus">删除用户</el-button>
        <el-button @click="delUser(1)" type="primary" icon="el-icon-plus">启用</el-button>
        <el-button @click="editorBatch" type="warning" icon="el-icon-plus">批量编辑</el-button>
        <el-button @click="delUser(2)" type="danger" icon="el-icon-minus">禁用</el-button>
        <!-- <el-button @click="dr" type="primary" icon="el-icon-plus">导入</el-button> -->
        <el-upload
          class="upload-demo"
          action
          :on-change="handleChange"
          :on-remove="handleRemove"
          :file-list="fileListUpload"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :auto-upload="true"
        >
          <el-button @click="dr" type="primary" icon="el-icon-plus">导入</el-button>
          <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div>
        </el-upload>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      stripe
      style="width: 100%"
    >
      <el-table-column type="index" label="#" width="50"></el-table-column>
      <el-table-column type="selection" width="55" :selectable="selectable"></el-table-column>
      <el-table-column prop="username" label="用户名" width="150"></el-table-column>
      <el-table-column prop="realname" label="真实姓名" width="100"></el-table-column>
      <el-table-column prop="mobile" label="手机号码" width="200"></el-table-column>
      <el-table-column prop="role_name" label="系统角色" width="200"></el-table-column>
      <el-table-column prop="unit_name" label="学校" width="200"></el-table-column>
      <el-table-column prop="grade_name" label="年级" width="150"></el-table-column>
      <el-table-column prop="class_name" label="班级" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status==1" type="text">已启用</el-button>
          <el-button v-else type="text">已禁用</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="warning" size="small" @click="editor(scope.row)">编辑</el-button>
          <el-button @click="del(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="total">
      <el-pagination
        @current-change="currentPage"
        background
        layout="prev, pager, next"
        :total="total"
      ></el-pagination>
    </el-row>

    <!-- 新增图书弹窗 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      width="30%"
    >
      <User
        ref="addData"
        @saveData="saveData"
        @saveDataEditor="saveDataEditor"
        @saveEditor="saveEditor"
        :title="title"
        :role="role"
        :school="school"
        :grade="grade"
        :classData="classData"
        :formData="formData"
        :formBatch="formBatch"
        :isEdit="isEdit"
        :pl="pl"
      ></User>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import User from "@/components/child/user";
import {
  userList,
  delUserList,
  addUserList,
  editorUserList,
  editorList,
  getGradeList,
  getClassList,
  getRoleList,
  getUnitList,
  batchUser,
  batchUserEditor,
  batchUserImport
} from "@/api/set";

export default {
  components: {
    User,
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      total: null,
      title: "添加用户",
      pageSize: 20,
      search: "",
      form: {
        page: 1,
        page_size: null,
        search: { username: "", unit_id: "", grade_id: "", class_id: "" },
        sort: "",
        order: "",
      },
      isEdit: false,
      dialogFormVisible: false, //新增弹窗
      list: null,
      listLoading: true,
      page: [
        {
          value: "40",
          label: "40",
        },
        {
          value: "80",
          label: "80",
        },
        {
          value: "120",
          label: "120",
        },
        {
          value: "200",
          label: "200",
        },
      ],
      grade: [],
      classData: [],
      role: [],
      school: [],
      batch: [],
      pl: true,
      value: "",
      tableData: [],
      formData: {},
      formBatch: {
        ids: [],
        role_id: null,
        unit_id: null,
        grade_id: null,
        class_id: null,
        password: null,
        status: 1,
      },
      fileTemp: null,
      fileListUpload:[]
    };
  },
  created() {
    this.fetchData();
    this.gradeList();
    this.classList();
    this.roleList();
    this.schoolList();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      let params = this.form;
      userList(params).then((response) => {
        this.tableData = response.data;
        this.total = response.total;
        this.listLoading = false;
      });
    },
    // 搜索
    searchData() {
      console.log(1);
      this.fetchData();
    },
    // 年级列表
    gradeList() {
      getGradeList().then((response) => {
        this.grade = response.data;
      });
    },
    // 班级列表
    classList() {
      getClassList().then((response) => {
        this.classData = response.data;
      });
    },
    // 角色列表
    roleList() {
      getRoleList().then((response) => {
        this.role = response.data;
      });
    },
    // 角色列表
    schoolList() {
      getUnitList().then((response) => {
        this.school = response.data;
      });
    },
    // 添加图书
    addUser() {
      setTimeout(() => {
        this.$refs.addData.$refs.formSave.clearValidate();
      }, 50);
      this.formData = {};
      this.dialogFormVisible = true;
      this.title = "添加用户";
      this.pl = true;
    },
    // 批量删除
    delUser(types) {
      if (this.batch.length == 0) {
        this.$message({
          type: "info",
          message: "请选择批量编辑对象",
        });
        return false;
      }
      let data = {
          ids: this.batch,
          type: types,
        },
        msg1 = null,
        msg2 = null;
      if (types == 3) {
        msg1 = "此操作将永久删除这些文件，是否确定";
        msg2 = "已取消删除";
      } else {
        msg1 = "此操作将永久修改这些文件状态，是否确定";
        msg2 = "已取消修改";
      }
      this.$confirm(msg1, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          batchUser(data).then((response) => {
            if (response.code == 1) {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.fetchData();
            } else {
              this.$message({
                type: "info",
                message: response.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: msg2,
          });
        });
    },
    // 编辑
    editor(row) {
      let $id = row.uid;
      this.$id = row.uid;
      setTimeout(() => {
        this.$refs.addData.$refs.formSave.clearValidate();
      }, 50);
      this.formData = {};
      this.dialogFormVisible = true;
      this.title = "编辑用户";
      this.pl = true;
      editorList($id).then((response) => {
        this.formData = response.data;
      });
    },
    editorBatch() {
      if (this.batch.length == 0) {
        this.$message({
          type: "info",
          message: "请选择批量编辑对象",
        });
        return false;
      }
      this.pl = false;
      this.title = "批量编辑";
      this.dialogFormVisible = true;
      console.log(this.formBatch);
    },
    // 保存新增数据
    saveData() {
      let data = this.formData;
      addUserList(data).then((response) => {
        if (response.code == 1) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.fetchData();
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: "info",
            message: response.message,
          });
        }
      });
    },
    // 保存编辑数据
    saveDataEditor() {
      let data = this.formData;
      editorUserList(data, this.$id).then((response) => {
        if (response.code == 1) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.fetchData();
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: "info",
            message: response.message,
          });
        }
      });
    },
    //  保存批量编辑
    saveEditor() {
      let data = this.formBatch;
      console.log(data);
      batchUserEditor(data).then((response) => {
        if (response.code == 1) {
          this.$message({
            type: "success",
            message: response.message,
          });
          this.fetchData();
          this.dialogFormVisible = false;
        } else {
          this.$message({
            type: "info",
            message: response.message,
          });
        }
      });
    },
    // 批量
    handleSelectionChange(val) {
      this.batch = [];
      this.formBatch.ids = [];
      val.forEach((item, index) => {
        this.batch.push(item.uid);
        this.formBatch.ids.push(item.uid);
      });
    },
    // 导入
    dr() {},
    // 删除
    del(row) {
      let $id = row.uid;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUserList($id).then((response) => {
            if (response.code == 1) {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.fetchData();
            } else {
              this.$message({
                type: "info",
                message: response.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    selectable(row, index) {
      if (row.uid === 1) {
        return false; //禁用状态
      } else {
        return true; //非禁用状态
      }
    },
    currentPage(val) {
      this.form.page = val;
      this.changeCategory();
    },
    save() {
      this.$refs.addData.validataForm();
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      let params = {
        file: this.fileTemp
      }
      batchUserImport(params).then(res=>{
        console.log(res)
      })
    },
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    // 导入函数
    importfxx(obj) {
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((v) => {
            let obj = {};
            obj.code = v["设备ID"];
            obj.type = v["设备型号"];
            arr.push(obj);
          });
          return arr;
        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
  },
  watch: {
    fileTemp() {
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
  },
};
</script>
<style>
.library-row {
  padding: 15px 0;
}

.add {
  display: flex;
  justify-content: flex-end;
}
.el-dialog__body {
  border: 1px solid #ddd;
}
.total {
  display: flex;
  justify-content: center;
  padding: 40px 0;
}
</style>